import React,{Component} from "react"

import Login from "../../components/login"

import BScroll  from "better-scroll";

import Tipmsg from "../../components/tipmsg"
import Loading from "../../components/loading"

import { Carousel, WingBlank } from 'antd-mobile';


import "./index.css"


import {getWorkDetail,getComment,Likepost,unLikepost,createComment,getUserInfo,delPost} from "../../api/course.js"
import config from "../../api/config"

let {accessToken} = config;

class Index extends Component{
	constructor(props){
		super(props);
		this.state = {
      msg:"",
      commentlist:[],
      page:0,
			headertitle:"",
			title:"",
      userimg:"",
      username:"",
      bannerImg:[],
      videoSrc:"",
      isDelbtn:false,
      CommentsCount:0,
      LikesCount:0,
      isLike:false,
      isLogin:false,
      showMask:false,
      showModal:false,
      showLoading:false,
      showTip:false,
      isVerified:false,
      tipmsg:"",
      nowIndex:0,
      showswiper:false,
      maskimg:false,
      showVideoSrc:true,
      poster:""


		}
	}

  closeHandl(){
     this.setState({showTip:false})
  }

  addComment(){
    if(localStorage.getItem("courseUserinfo")){
           if(this.state.msg.trim()==""){
     
             this.setState({
                showTip:true,
                tipmsg:"请输入评论"
             })
             
             return;
           }

           if(this.state.msg.trim().length>140){
              this.setState({
                showTip:true,
                tipmsg:"评论字数长度不得超过140"
              })
              return;
           }
           //已经登录
           let token =JSON.parse(localStorage.getItem("courseUserinfo")).AccessToken;
           this.setState({
              showLoading:true
           })
           
           getUserInfo(token).then(res=>{
               if(res.data.PhoneNumber!=""){//已经绑定手机号
                   
                    let postid = this.props.match.params.id;
        
                    createComment(token,postid,{
                        "Text": this.state.msg
                    }).then(res=>{
                        this.setState({
                              commentlist:[],
                              msg:"",
                              page:0,
                              showLoading:false,
                              CommentsCount:this.state.CommentsCount+1
                        },()=>{
                              this.getCommentData(this.state.page)
                        })
                         
                    }).catch(err=>{
                       //alert("发送失败，包含不当内容，请编辑重发")
                       this.setState({
                          showMask:false,
                          showLoading:false,
                          msg:"",
                          showTip:true,
                          tipmsg:"您的评论存在违禁词"
                       })


                    })
               }else{  //未手机号码
                  //alert("去绑定手机号码")
                  this.props.history.push("/fanscourse/bindphone")
               }
           })
        
        }else{  //没有登录
             var ua = navigator.userAgent.toLowerCase();//获取判断用的对象
             if (ua.match(/MicroMessenger/i) == "micromessenger") {
                //在微信中打开
                window.WechatAuthorize();
                return 
             }
             if (ua.match(/WeiBo/i) == "weibo") {
               //在新浪微博客户端打开
                 window.WeiboAuthorize();
                 return 
             }
             
             this.setState({
                isLogin:true
             })
       }
  }

  
  componentDidMount(){
    this.getData();
    this.getCommentData(0);
    this.loadMore();
    
  }

  initImg(){
    var maskimg = this.refs.maskimg;
    var img = maskimg.querySelector("img");
    var oH = document.documentElement.clientHeight;
    
    img.height = oH/2;
    img.style.top = (oH-img.height)/2+"px"
   
   /* if(img.height>=oW){
         img.style.top = 0;
         img.style.height = oW + "px"
         return   
    }*/
    
   /* if(img.height){
       img.style.marginTop = -img.height/2 + "px";
      
    }else{
      img.onload = function(){
         img.style.marginTop = -img.height/2 + "px"
      }
    }
   
    */
   
  }

  
  init(){
    var swiper = this.refs.swiper;
  

    var imgs = swiper.querySelectorAll("img");
    var a = swiper.querySelectorAll("a");
  
    var oW = document.documentElement.clientHeight;
   

    Array.from(a).forEach(item=>{
     // console.log(item)
      item.style.height = oW+"px";
     
    })
    Array.from(imgs).forEach(item=>{
       item.style.top = "50%";
       item.onload = function(){
         console.log(this.height)
         this.style.marginTop = -this.height/2 + "px"
       }
      
       //item.style.marginTop = 
    })
  

  }
  
  closeModal(){
    this.setState({
       isLogin:false
    })
  }
  
  unlikeHandl(){
      let token = JSON.parse(localStorage.getItem("courseUserinfo")).AccessToken;
      let {id} = this.props.match.params;
      this.setState({
        showLoading:true
      })
      unLikepost(token,id).then(res=>{
          this.setState({isLike:false,LikesCount:this.state.LikesCount-1,showLoading:false})
      })
  }


  likeHandl(){
       if(localStorage.getItem("courseUserinfo")){
             let token = JSON.parse(localStorage.getItem("courseUserinfo")).AccessToken;
             let {id} = this.props.match.params;
             this.setState({
              showLoading:true
             })
             Likepost(token,id).then(res=>{
                
                 this.setState({isLike:true,LikesCount:this.state.LikesCount+1,showLoading:false})
             })
            
         }else{
             var ua = navigator.userAgent.toLowerCase();//获取判断用的对象
             if (ua.match(/MicroMessenger/i) == "micromessenger") {
                //在微信中打开
                window.WechatAuthorize();
                return 
             }
             if (ua.match(/WeiBo/i) == "weibo") {
                 //在新浪微博客户端打开
                 window.WeiboAuthorize();
                 return 
             }
             
             this.setState({
                isLogin:true
             })

         }
  }





  getData(){ //获取详情数据
    let {id} = this.props.match.params;
    let token;
    let appUserid;
    if(localStorage.getItem("courseUserinfo")){
          let {AccessToken,AppUserId} = JSON.parse(localStorage.getItem("courseUserinfo"));
          token =  AccessToken;
          appUserid = AppUserId;
        
    }else{
          token = accessToken;
          appUserid = "";
    }
    
  
    getWorkDetail(token,id).then(res=>{
   
        this.setState({
            //headertitle:res.data.AppUserModel.AppUserId===AppUserId?"我的作业":"优秀学员作业",
            isDelbtn:res.data.AppUserModel.AppUserId===appUserid && !res.data.IsVerified?true:false,
            title:res.data.Title,
            userimg:res.data.AppUserModel.ImageUrl,
            username:res.data.AppUserModel.NickName,
            bannerImg:res.data.PhotoList[0]?res.data.PhotoList:[],
           // bannerImg:res.data.PhotoList[0]?res.data.PhotoList[0].ThumbnailUrl:"",
            videoSrc:res.data.VideoList[0]?res.data.VideoList[0].Mp4Url:"",
            poster:res.data.VideoList[0]?res.data.VideoList[0].ThumbnailUrl:"",
            CommentsCount:res.data.CommentsCount,
            LikesCount:res.data.LikesCount,
            isLike:res.data.IsLiked
       })
    })
  }

  getCommentData(page){
      let {id} = this.props.match.params;
      getComment(accessToken,id,page)
      .then(res=>{
      
        this.setState({
            commentlist:[...this.state.commentlist,...res.data]
        })
      })

  }


  loadMore(){
      this.workWrap = new BScroll(this.refs.workWrap,{
            scrollY: true,
            click: true,
            useTransition:false,
            pullUpLoad: {
              threshold:-20 
            },
            pullDownRefresh: {
               threshold:30,
               stop: 0
            }
        })
        
        
        this.workWrap.on('pullingUp',()=>{
            //console.log("到底部了")
            this.setState({
               page:this.state.page+10
            },()=>{
              this.getCommentData(this.state.page)
            })
            
            setTimeout(() => {
                this.workWrap.finishPullUp();
                this.workWrap.refresh();
            },500)
         
        })
    }
  

 delHandl(){
    let token = JSON.parse(localStorage.getItem("courseUserinfo")).AccessToken;
    let {id} = this.props.match.params;
    this.setState({showLoading:true});
    delPost(token,id).then(res=>{
       console.log(res)
       this.setState({showLoading:false})
       this.props.history.goBack();
    })
 }
  



	render(){
		let { 
         headertitle, 
         title, 
         userimg,
         username,
         bannerImg,
         videoSrc,
         isDelbtn ,
         CommentsCount,
         LikesCount,
         isLike,
         commentlist,
         isLogin,
         showModal,
         showTip,
         showVideoSrc
    } = this.state;

		return(
           <div className="workdetail">
               <div className="workdetail-header">
                    <span className="back" onClick={()=>{this.props.history.goBack()}}></span>
                    <h3>{isDelbtn?"我的作业":"优秀学员作业"}</h3>
               </div>
               
               <div className="wrap" ref="workWrap">
                 <div className="work-content">

               <div className="banner">
                      {bannerImg.length>1?<WingBlank >
                          <Carousel
                           autoplay={false}
                           dots={true}
                           infinite
                           selectedIndex={0}
                           afterChange={index => this.setState({nowIndex:index})}
                           >
                           {bannerImg.map(item => (
                             <a key={item.PhotoId}
                                style={{ display: 'inline-block', width: '100%' }}
                                onClick={()=>{
                                  this.setState({showswiper:true},()=>{
                                    this.init()
                                  })
                                }}>
                               <img
                                 src={item.ThumbnailUrl}
                                 alt=""
                                 style={{ width: '100%', verticalAlign: 'top',height:"4rem",objectFit: "cover"}}
                                 onLoad={() => {window.dispatchEvent(new Event('resize'));}}/>
                             </a>
                           ))}
                         </Carousel>
                      </WingBlank>:null}
                      {bannerImg.length==1?<img src={bannerImg[0]?bannerImg[0].ThumbnailUrl:""} 
                      onClick={()=>{
                        this.setState({maskimg:true})
                        this.initImg()
                      }}/>:null}

                      {videoSrc?<video src={videoSrc} controls poster={this.state.poster} ref="video" ></video>:null}
                      {videoSrc?<img src={this.state.poster} className="videoimg" style={{"display":showVideoSrc?"block":"none"}}/>:null} 
                      {videoSrc?<span className="playbtn" style={{"display":showVideoSrc?"block":"none"}}
                        onClick={()=>{
                         var video = this.refs.video;
                         this.setState({showVideoSrc:false})
                         video.play()
                      }}></span>:null}   
               </div>

           


               
               <div className="workinfo">
                    <h3>{title}</h3>
                    {isDelbtn?<span className="del" onClick={()=>{this.setState({showModal:true})}}>删除</span>:null}
                    
                    <dl>
                        <dt><img src={userimg} alt="" /></dt>
                        <dd>
                            <p>{username}</p>
                            <span className="commentnum"><i></i>{CommentsCount}</span>
                            <span className="likenum"><i></i>{LikesCount}</span>
                        </dd>
                    </dl>
               </div>


               <div className="commentbox">
                   <h3>评论({CommentsCount})</h3>
                   <ul>
                      {commentlist.map(item=>{
                         return <li key={item.CommentId}>
                         <dl>
                           <dt><img src={item.UserModel.ImageUrl} alt=""/></dt>
                           <dd>{item.UserModel.NickName}</dd> 
                         </dl>
                         <span>{item.LastUpdatedDate.split("T")[0]}</span>
                         <p>{item.Text}</p>
                      </li> 
                      })}
                      
                     
                   </ul>
               </div>
               </div>
              </div>
              
               <div className="form">
                  <p><i></i>
                      <input type="text" placeholder="写下你的评论…" 
                            value={this.state.msg} 
                            onChange={(ev)=>{
                              this.setState({
                                msg:ev.target.value
                              })
                            }} 
                            onClick={()=>{
                              if(localStorage.getItem("courseUserinfo")){
                                  //已经登录
                                  let token =JSON.parse(localStorage.getItem("courseUserinfo")).AccessToken;
                                  getUserInfo(token).then(res=>{
                                      if(res.data.PhoneNumber==""){//未绑定手机号
                                         this.props.history.push("/fanscourse/bindphone")
                                      }
                                  })
        
                              }else{  //没有登录
                                   var ua = navigator.userAgent.toLowerCase();//获取判断用的对象
                                   if (ua.match(/MicroMessenger/i) == "micromessenger") {
                                      //在微信中打开
                                      window.WechatAuthorize();
                                      return 
                                   }
                                   if (ua.match(/WeiBo/i) == "weibo") {
                                     //在新浪微博客户端打开
                                       window.WeiboAuthorize();
                                       return 
                                   }
                                   
                                   this.setState({
                                      isLogin:true
                                   })
                              }
                            
                            }}/>
                  </p>
                  <span onClick={this.addComment.bind(this)}>发送</span>
                  {isLike?<em className="like" onClick={this.unlikeHandl.bind(this)}></em>:<em onClick={this.likeHandl.bind(this)}></em>}
               </div>

               {isLogin?<Login closeModal={this.closeModal.bind(this)}/>:null}

               {this.state.showMask?<div className="mask"><p>提交评论中...</p></div>:null}

                {showModal?<div className="delmodal">
                   <div className="modal">
                       <span></span>
                       <h3>确认删除?</h3>
                       <p className="delbtn">
                         <em onClick={()=>{this.setState({showModal:false})}}>取消</em>
                         <em className="orange" onClick={this.delHandl.bind(this)}>删除</em>
                       </p>
                   </div>
                </div>:null}
                  
                
               {this.state.showTip?<Tipmsg msg={this.state.tipmsg} closeHandl={this.closeHandl.bind(this)}/>:null}
               <span className="goindex" onClick={()=>{this.props.history.push("/fanscourse")}}></span> 
               {this.state.showLoading?<Loading />:null}

               
                {this.state.showswiper?<div className="swiper" ref="swiper" onClick={()=>{this.setState({showswiper:false})}}>
                   {bannerImg.length>1?<WingBlank>
                          <Carousel
                           autoplay={false}
                           infinite
                           selectedIndex={this.state.nowIndex}
                           >
                           {bannerImg.map(item => (
                             <a key={item.PhotoId}
                                style={{ display: 'block', width: '100%'}}>
                               <img
                                 src={item.ThumbnailUrl}
                                 alt=""
                                 style={{ width: '100%'}}
                                 onLoad={() => {window.dispatchEvent(new Event('resize'));}}/>
                             </a>
                           ))}
                         </Carousel>
                      </WingBlank>:null}
                </div>:null}

                {bannerImg.length==1?
                  <div className="maskimg" ref="maskimg" style={{"display":this.state.maskimg?"block":"none"}} 
                        onClick={()=>{this.setState({maskimg:false})}}><img src={bannerImg[0]?bannerImg[0].ThumbnailUrl:""} /></div>:null
                }
                


           </div>
		)
	}
}

export default Index